package com.qc.controller.merchant;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.qc.common.ImageUtils;
import com.qc.common.QiNiuUtil;
import com.qc.common.SMSClient;
import com.qc.common.StringUtil;
import com.qc.common.Util;
import com.qc.common.WebUtil;
import com.qc.controller.UserCookie;
import com.qc.entity.BusinessCategoryEntity;
import com.qc.entity.MerchantEntity;
import com.qc.service.BusinessCategoryService;
import com.qc.service.MerchantService;
import com.qc.service.UserService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 商家首页
 * @author X
 *
 */
@Controller
@RequestMapping("/merchant")
public class MerchantController {

	@Resource
    private UserService userService;
	
    @Resource(name="merchantService")
    private MerchantService merchantService;
    
    @Resource(name="businessCategoryService")
    private BusinessCategoryService businessCategoryService;
    
    
    /**
     * 登录成功跳转页面
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/toJump", produces = "text/html;charset=UTF-8")
    public ModelAndView toJump(HttpServletRequest request,HttpServletResponse response) {
        ModelAndView mav = new ModelAndView();
        MerchantEntity merchantEntity2 = (MerchantEntity) request.getSession().getAttribute("merchantEntity");
        
        MerchantEntity merchantEntity = merchantService.getMerchantId(merchantEntity2.getShopId());
        
        List<BusinessCategoryEntity> listCategory = businessCategoryService.getAllLevleOne();
        if (0 == merchantEntity.getIsAuth()){
            mav = new ModelAndView("/business/add");
            mav.addObject("listCategory",listCategory);
        }else if (1 == merchantEntity.getIsAuth()) {
            mav = new ModelAndView("/business/default");
        }else if (2 == merchantEntity.getIsAuth()) {
            mav = new ModelAndView("redirect:/merchant/toInform.do");
        }else if (3 == merchantEntity.getIsAuth()) {
        	mav = new ModelAndView("/business/add2");
        	
        	mav.addObject("merchantEntity",merchantEntity);
        }
        return mav;
    }
    
    @RequestMapping(value = "/toCuowu", produces = "text/html;charset=UTF-8")
    public ModelAndView toCuowu(HttpServletRequest request,HttpServletResponse response) {
    	
        ModelAndView mav = new ModelAndView("/business/ref_add");
        
        long shopId = Long.parseLong(request.getParameter("shopId"));
        
        MerchantEntity merchantEntity = merchantService.getMerchantId(shopId);
        
        List<BusinessCategoryEntity> listCategoryOne = businessCategoryService.getAllLevleOne();
        List<BusinessCategoryEntity> listCategoryTwo = businessCategoryService.getAllLevleTwo();
        
        mav.addObject("listCategoryOne",listCategoryOne);
        mav.addObject("listCategoryTwo",listCategoryTwo);
        
        
        mav.addObject("merchantEntity",merchantEntity);
        
        return mav;
    }
    

    /**
     * 商家获取二级分类
     * @param request
     * @return
     */
    @RequestMapping(value = "/toSelectCategoryTwo", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String toSelectCategoryTwo(HttpServletRequest request) {
    	
    	 String parent = request.getParameter("parent");
    	
    	List<BusinessCategoryEntity> listCategory = businessCategoryService.getAllLevleTwo(parent);
    	
    	return JSONArray.fromObject(listCategory).toString();
    	
    }
    
    /**
     * 商家详细
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/toInform", produces = "text/html;charset=UTF-8")
    public ModelAndView toInform(HttpServletRequest request,HttpServletResponse response) {
        ModelAndView mav = new ModelAndView("/business/inform");
        
        MerchantEntity merchantEntity2 = (MerchantEntity) request.getSession().getAttribute("merchantEntity");
        
        MerchantEntity merchantEntity = merchantService.getMerchantId(merchantEntity2.getShopId());
        mav.addObject("merchantEntity",merchantEntity);
        return mav;
    }
    
    
    /**
     * 商家添加完整信息
     * @param request
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/toMerchantRegister", produces = "text/html;charset=UTF-8")
    public ModelAndView toMerchantRegister(HttpServletRequest request,@RequestParam("file") CommonsMultipartFile[] file) throws Exception  {
        
    	ModelAndView mav = new ModelAndView("redirect:/merchant/toJump.do");
    	
        MerchantEntity merchantEntity = (MerchantEntity) request.getSession().getAttribute("merchantEntity");
        
        String store_name = request.getParameter("store_name");
        String owner_name = request.getParameter("owner_name");
        String select_1 = request.getParameter("select_1");
        String select_2 = request.getParameter("select_2");
        String select_3 = request.getParameter("select_3");
        String address = request.getParameter("address");
        String tel = request.getParameter("tel");
        double price = Double.parseDouble(request.getParameter("price"));
        String description = request.getParameter("description");
        String manager_name = request.getParameter("manager_name");
        String manager_phone = request.getParameter("manager_phone");
        long shopType = Long.parseLong(request.getParameter("shopType"));
        long shopType2 = Long.parseLong(request.getParameter("shopType2"));
        
        
		try {
			//获取纬度经度
	        String  s = WebUtil.sendGet("http://restapi.amap.com/v3/geocode/geo", "key=c3a4987b067e3046e50d686493b336bc&output=json&address="+select_1+select_2+select_3+address+"");
	        
	        JSONObject jsonObject =JSONObject.fromObject(s);
			JSONArray jsonArray = jsonObject.getJSONArray("geocodes");
			
			JSONObject row = null;
			String dizhi = "";
			for (int i = 0; i < jsonArray.size(); i++) {  
			   row = jsonArray.getJSONObject(i);  
			   dizhi = (String) row.get("location");
			}
			
			String[] b = dizhi.split(",");
			merchantEntity.setShopLatitude(b[1]);
			merchantEntity.setShopLongitude(b[0]);
			
		} catch (Exception e1) {
		}
		
        
        String url = request.getSession().getServletContext().getRealPath("/")+("/fileImage");
        
        if(file!=null&&file.length>0){
            //循环获取file数组中得文件  
            for(int i = 0;i<file.length;i++){
                MultipartFile files = file[i];
                
                //获取图片名称
                String fileName = files.getOriginalFilename();
                
                if (StringUtil.isNotEmpty(fileName)) {
                	 //目录不存在 新建一个
                    File f1=new File(url); 
                    if(!f1.isDirectory()) {
                        f1.mkdir();
                    }
                    //创建时间参数
                    SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyyMMddhhmmssSSS");// 文件重命名
                    String namefile = bartDateFormat.format(new Date());
                    
                    InputStream stream = files.getInputStream();// 把文件读入
                    
                    //图片名字
                    fileName = namefile + fileName.substring(fileName.lastIndexOf("."));// 保存文件路径和文件名
                    OutputStream bos = new FileOutputStream(url + "/" + fileName);// 建立一个上传文件的路径
                    int bytesRead = 0;
                    byte[] buffer = new byte[10240];
                    
                    while( (bytesRead=stream.read(buffer)) != -1 ){  
                    	bos.write(buffer, 0, bytesRead);  
                    }  
                    
                    bos.close();
                    stream.close();
                    
                    String path = url + "/" + fileName;
                    
                    ImageUtils.scale(path, path, 2, true);
                    
                    try {
                        QiNiuUtil.upload(path, "web_dev_14_qiniu_"+fileName);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    
                    //0 商家logo
                    if (i == 0) {
                        merchantEntity.setMerLogo("web_dev_14_qiniu_"+fileName);
                    }else if (i == 1) {
                       //1 身份证正面照
                        merchantEntity.setCardFrontPhoto("web_dev_14_qiniu_"+fileName);
                    }else if (i == 2) {
                        //身份证反面照
                        merchantEntity.setCardBackPhoto("web_dev_14_qiniu_"+fileName);
                    }else if (i == 3) {
                        //营业执照
                        merchantEntity.setBusinessLicensePhoto("web_dev_14_qiniu_"+fileName);
                    }
                }
            }
        }
        
        merchantEntity.setAddressDetail(address);
        merchantEntity.setPerCapitaPrice(price);
        merchantEntity.setBossName(manager_name);
        merchantEntity.setCity(select_2);
        merchantEntity.setProvince(select_1);
        merchantEntity.setRegion(select_3);
        merchantEntity.setIntro(description);
        merchantEntity.setIsAuth(1);
        merchantEntity.setLegalPersonName(owner_name);
        merchantEntity.setMobile(manager_phone);
        merchantEntity.setShopType(shopType);
        merchantEntity.setShopTypeTwo(shopType2);
        merchantEntity.setShopName(store_name);
        merchantEntity.setTelphone(tel);
        
        merchantService.saveMerchant(merchantEntity);
        
        return  mav;
    }
    
    
    /**
     * 商家详细信息 修改
     * @param request
     * @param response
     * @param merchantEntity
     * @return
     */
    @RequestMapping(value = "/toUpdateInform", method = RequestMethod.POST)
    public @ResponseBody int toUpdateInform(HttpServletRequest request,HttpServletResponse response,MerchantEntity merchantEntity) {
        
        MerchantEntity entity = merchantService.getMerchantId(merchantEntity.getShopId());
        
        
        //获取纬度经度
        String  s = WebUtil.sendGet("http://restapi.amap.com/v3/geocode/geo", "key=c3a4987b067e3046e50d686493b336bc&output=json&address="+entity.getProvince()+entity.getCity()+entity.getRegion()+merchantEntity.getAddressDetail()+"");
        
        JSONObject jsonObject =JSONObject.fromObject(s);
		JSONArray jsonArray;
		try {
			jsonArray = jsonObject.getJSONArray("geocodes");
			
			JSONObject row = null;
			String dizhi = "";
			for (int i = 0; i < jsonArray.size(); i++) {  
			   row = jsonArray.getJSONObject(i);  
			   dizhi = (String) row.get("location");
			}
			
			String[] b = dizhi.split(",");
			entity.setShopLatitude(b[1]);
			entity.setShopLongitude(b[0]);
			
		} catch (Exception e1) {
		}
        
        entity.setBossName(merchantEntity.getBossName());
        entity.setMobile(merchantEntity.getMobile());
        entity.setTelphone(merchantEntity.getTelphone());
        entity.setAddressDetail(merchantEntity.getAddressDetail());
        entity.setAvgPrice(merchantEntity.getAvgPrice());
        entity.setPerCapitaPrice(merchantEntity.getPerCapitaPrice());
        
        
        
        int flag = merchantService.saveMerchant(entity);
        
        return flag;
    }
    
    /**
     * 商家修改手机号
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/toSenMobile", produces = "text/html;charset=UTF-8")
    public ModelAndView toSenMobile(HttpServletRequest request,HttpServletResponse response) {
        ModelAndView mav = new ModelAndView("/business/xiugaishouji");
        
        String shopId = request.getParameter("shopId");
        
        mav.addObject("shopId",shopId);
        return mav;
    }
    
    @RequestMapping(value = "/toSmsSendPws", method = RequestMethod.POST)
    public @ResponseBody String toSmsSendPws(HttpServletRequest request) {
        int code = Util.get6code();
        String userName = request.getParameter("userName");
        long shopId = Long.parseLong(request.getParameter("shopId"));
        
        String sucess = "0";
        MerchantEntity merchantEntity = merchantService.getMerchantId(shopId);
        if (merchantEntity.getUserName() != null) {
            
            Boolean flag = SMSClient.send(userName, "您的注册验证码是"+code+"，为了保护您的账户安全，验证短信请勿转发给其他人。【圈城】");
            if (flag) {
                String codeStr = userService.getMobileCode(userName);
                if (codeStr != null && !codeStr.equals("")) {
                    userService.updateCodeByMobile(userName, code+"");
                } else {
                    userService.saveCode(userName, code+"");
                }
                sucess = "1";
            }else{
            	sucess = "0";
            }
        }else {
        	sucess = "2";
        }
		return sucess;
    }
    
    /**
     * 修改手机号
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/updateMobile", method = RequestMethod.POST)
    public @ResponseBody int updateMobile(HttpServletRequest request,HttpServletResponse response) {
    	
    	long shopId = Long.parseLong(request.getParameter("shopId"));
    	
        String userName = request.getParameter("userName");
        String phone_code = request.getParameter("phone_code");
        String code = userService.getMobileCode(userName);
        
        int flag = 0;
        
        MerchantEntity entity = merchantService.getMerchantUserName(userName);
        if (StringUtil.isNotEmpty(entity.getUserName())) {
        	flag = 2;
        	
        	return flag;
        }
        
        if (code == null || !code.equals(phone_code)) {
            return flag;
        }
        
        MerchantEntity merchantEntity = merchantService.getMerchantShopId(shopId);
        if (StringUtil.isNotEmpty(merchantEntity.getUserName())) {
        	merchantEntity.setUserName(userName);
        	
        	merchantService.saveMerchant(merchantEntity);
        	
        	UserCookie cookie= new UserCookie();
            String ip = getIpAddr(request);
            String value=ip+"-&&&&&&"+userName+"-&&&&&&"+merchantEntity.getUserPwd();
            cookie.addCookie(response,"merAutouser",value);
            
            request.getSession().setAttribute("merchantEntity", merchantEntity);
            
            flag = 1;

        }
        
        return flag;
       
    }
    
    /**
     * 商家 修改密码
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/toSenpws", produces = "text/html;charset=UTF-8")
    public ModelAndView toSenpws(HttpServletRequest request,HttpServletResponse response) {
        ModelAndView mav = new ModelAndView("/business/xiugaishoujimima");
        
        String shopId = request.getParameter("shopId");
        
        mav.addObject("shopId",shopId);
        return mav;
    }
    
    @RequestMapping(value = "/updatePws", method = RequestMethod.POST)
    public @ResponseBody int updatePws(HttpServletRequest request,HttpServletResponse response) {
    	long shopId = Long.parseLong(request.getParameter("shopId"));
    	String old_password = request.getParameter("old_password");
    	String password = request.getParameter("password");
    	
    	 MerchantEntity merchantEntity = merchantService.getMerchantShopId(shopId);
    	 
    	 if (old_password.equals(merchantEntity.getUserPwd())) {
    		 
    		 merchantEntity.setUserPwd(password);
    		 merchantEntity.setShopId(shopId);
    		 
    		 merchantService.saveMerchant(merchantEntity);
    		 
    		 return 1;
    	 }else {
    		 return 2;
    	 }
    	 
    }
    
    
    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    
    
    @RequestMapping(value = "/toException", produces = "text/html;charset=UTF-8")
    public ModelAndView toException(HttpServletRequest request,HttpServletResponse response) {
        ModelAndView mav = new ModelAndView("/business/add_no");
        
        MerchantEntity merchantEntity2 = (MerchantEntity) request.getSession().getAttribute("merchantEntity");
        
        MerchantEntity merchantEntity = merchantService.getMerchantId(merchantEntity2.getShopId());
        mav.addObject("merchantEntity",merchantEntity);
        return mav;
    }
    
}
